import {
    SET_THEME,
    SET_USER_INFO,
} from '../constants';
import {get} from '$/utils'
import api from '$/config/api'
import {Toast} from 'antd-mobile-rn'
import Cookies from 'js-cookie'
import {setItem} from '$/utils/storage'
import NavUtils from '$/utils/NavUtils'



/*设置主题*/
export const setTheme = color => {
    return {
        type: SET_THEME,
        color,
    }
}

/*设置用户信息*/
export const setUserInfo = userInfo => {
    return {
        type: SET_USER_INFO,
        userInfo: userInfo
    }
}

const loginSuccess = (dispatch, res) => {
    Cookies.set('token', res.token)
    setItem('userInfo', res)
    dispatch(setUserInfo(res))
    NavUtils.go('TabBar')
}

/*登录*/
export const login = o => {
    return dispatch => {
        Toast.loading('', 0);
        get(api.phoneLoginUrl, o).then(res => {
            if(res && res.code === 200){
                res['phone'] = o.phone;
                res['password'] = o.password;
                res['isLogin'] = true;
                loginSuccess(dispatch, res);
                Toast.hide()
            }else{
                Toast.fail(res.message || '登录失败')
            }
        }).catch(err => {
            Toast.fail('登录失败')
        })

    }
}


/*发送验证码*/
export const sendCode = (phone, func) => {
    return dispatch => {
         get(api.sendCodeUrl, { phone }).then(res => {
             if(res && res.code === 200){
                 Toast.success('验证码发送成功！');
                 func && func()
             }
         }).catch(err => {
             Toast.fail('验证码发送失败,请重试！')
         })
    }
}
